/*
 * @Author: LIFM0623 1944099171@qq.com
 * @Date: 2024-01-22 15:23:12
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-05-15 21:12:50
 * @FilePath: \Scene_Back\src\user\user.service.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
  BadRequestException,
  ConflictException,
  Inject,
  Injectable,
  InternalServerErrorException,
} from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { v4 as uuidv4 } from 'uuid';
import { RegisterUserDto } from './dto/register-user.dto';
import * as jwt from 'jsonwebtoken';
import { ConfigService } from '@nestjs/config';
import { Response } from 'express';
import * as fs from 'fs';
import * as path from 'path';
import { WINSTON_LOGGER_TOKEN } from 'src/winston/winston.module';
import { CreateFolderDto } from 'src/folder/dto/create-folder.dto';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private configService: ConfigService,
  ) { }

  @Inject(WINSTON_LOGGER_TOKEN)
  private logger;
  async register(
    registerUserDto: RegisterUserDto,
    registerToken: string,
  ): Promise<string> {
    try {
      // const secretKey = this.configService.get('SECRET', 'yssyyds');
      // const { code } = jwt.verify(registerToken, secretKey) as {
      //   code: string;
      //   iat: number;
      //   exp: number;
      // };

      // if (code !== registerUserDto.code) {
      //   throw new BadRequestException('验证码验证失败，请重新注册！');
      // }

      const existingUser = await this.userRepository.findOne({
        where: { email: registerUserDto.email },
      });

      if (existingUser) {
        throw new ConflictException('该邮箱已被注册！');
      }

      const registerItem = this.userRepository.create(registerUserDto);

      await this.userRepository.insert(registerItem);

      return '注册成功，请去登录！';
    } catch (error) {
      this.logger.error(
        `注册失败: ${error.message}`,
        error.stack,
        `${UserService.name}-${this.register.name}`,
      );

      if (
        error instanceof BadRequestException ||
        error instanceof ConflictException
      ) {
        throw error;
      }

      throw new InternalServerErrorException(
        '注册过程中发生错误，请稍后重试。',
      );
    }
  }

  async getUserInfo(accessToken: string) {
    try {
      const secretKey = this.configService.get('SECRET', 'yssyyds');
      const { email } = jwt.verify(accessToken, secretKey) as {
        email: string;
        iat: number;
        exp: number;
      };
      const findResult = await this.userRepository.findOne({
        where: { email: email },
      });
      const returnResult = {
        id: findResult.id,
        email: findResult.email,
        username: findResult.username,
        role: findResult.role,
        avatar: findResult.avatar,
      };
      return returnResult;
    } catch (error) {
      this.logger.error(
        `令牌失效：${error}`,
        `${UserService.name}-${this.register.name}`,
      );
      throw new BadRequestException('令牌失效');
    }
  }

  async getUseravatar(avatar: string, res: Response<any, Record<string, any>>) {
    const filePath = path.resolve(process.env.FILE_PATH + '/avatar/' + avatar);
    const fileStream = fs.createReadStream(filePath);
    res.setHeader('Content-Type', 'image/png');
    fileStream.pipe(res);
  }

  async updateUserInfo(
    updateUserDto: UpdateUserDto,
    avatar_file?: Express.Multer.File,
  ) {
    const update = new UpdateUserDto();
    if (avatar_file) {
      update.avatar = avatar_file.filename;
    }
    update.email = updateUserDto.email;
    update.username = updateUserDto.username;
    const user = this.userRepository.create(update);
    const result = await this.userRepository.update(
      { email: user.email },
      user,
    );
    if (result) {
      return '修改成功!';
    } else {
      return '修改失败!';
    }
  }

  create(createUserDto: CreateUserDto) {
    const user = this.userRepository.create(createUserDto);
    this.userRepository.insert(user);
  }

  async findAll(): Promise<User[]> {
    return this.userRepository.find();
  }

  async findOne(email: string): Promise<User> {
    return this.userRepository.findOne({ where: { email: email } });
  }

  async update(id: string, updateUserDto: UpdateUserDto) {
    const oldUser = await this.userRepository.findOne({ where: { id: id } });
    if (!oldUser) {
      return '用户不存在';
    }
    const { id: userId, ...restUpdateUserDto } = updateUserDto;
    const updatedUser = Object.assign(oldUser, restUpdateUserDto);
    await this.userRepository.save(updatedUser);
    return '修改成功!';
  }

  async remove(id: string) {
    const list = await this.userRepository.delete({ id: id });
    if (list) {
      return '删除成功!';
    } else {
      return '删除失败!';
    }
  }
}
